package com.example.localvideoplayer

import android.Manifest
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import kotlinx.coroutines.*


class PlayActivity : AppCompatActivity() {
    private lateinit var player: ExoPlayer
    private lateinit var mediaItem: MediaItem
    private lateinit var stopView: View
    lateinit var playerView: com.google.android.exoplayer2.ui.PlayerView
    private val permissions = arrayOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )
    private val mPermissionList = ArrayList<String>()
    private val mRequestCode = 0x1//权限请求码

    @RequiresApi(Build.VERSION_CODES.P)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (supportActionBar != null) {
            supportActionBar?.hide()
        }
        val lp: WindowManager.LayoutParams = this.window.attributes
        lp.layoutInDisplayCutoutMode =
            WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        this.window.attributes = lp

//        window.setFlags(
//            android.R.style.Theme_NoTitleBar_Fullscreen,
//            android.R.style.Theme_Material_NoActionBar_TranslucentDecor
//        )

        setContentView(R.layout.activity_play2)
        player = ExoPlayer.Builder(this).build()
        playerView =
            findViewById(R.id.exo_player)
        playerView.player = player
        playerView.setShowNextButton(false)
        playerView.setShowPreviousButton(false)
        initPermission()
        player.repeatMode = ExoPlayer.REPEAT_MODE_ONE
        val uriName = intent.getStringExtra("uri")
        val uri = Uri.parse(uriName)
        mediaItem = MediaItem.fromUri(uri)
        player.setMediaItem(mediaItem)//准备媒体资源
        player.prepare()
        player.play()

        stopView = findViewById(R.id.stop)
        stopView.visibility = View.VISIBLE
        stopView.setOnClickListener {
            finish()
        }

        MainScope().launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                delay(5000)
            }
            stopView.visibility = View.INVISIBLE
        }
        playerView.setOnClickListener {
            if (stopView.visibility == View.INVISIBLE) {
                stopView.visibility = View.VISIBLE
                MainScope().launch(Dispatchers.Main) {
                    withContext(Dispatchers.IO) {
                        delay(5000)
                    }
                      stopView.visibility = View.INVISIBLE
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        player.stop()
        player.release()

    }


    @RequiresApi(Build.VERSION_CODES.R)
    override fun onConfigurationChanged(newConfig: Configuration) {
        Log.i("localvideo", "orientation changed")
        super.onConfigurationChanged(newConfig)
        if (supportActionBar != null) {
            supportActionBar?.hide()
        }
        window.setFlags(
            android.R.style.Theme_NoTitleBar_Fullscreen,
            android.R.style.Theme_Material_NoActionBar_TranslucentDecor
        )
//        window.addFlags(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES)
//        window.setFlags(
//            WindowManager.LayoutParams.FLAG_FULLSCREEN,
//            WindowManager.LayoutParams.FLAG_FULLSCREEN
//        )
    }


    override fun onRestart() {
        super.onRestart()
        player.play()
    }

    override fun onResume() {
        super.onResume()
        player.play()
    }

    private fun initPermission() {
        mPermissionList.clear()
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(
                    this@PlayActivity,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                mPermissionList.add(permission)
            }
        }
        if (mPermissionList.isNotEmpty()) {
            // 后续操作...
            ActivityCompat.requestPermissions(this@PlayActivity, permissions, mRequestCode)
        }
    }

    //重写
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            0x1 -> for (element in grantResults) {
                if (element != PackageManager.PERMISSION_GRANTED) Toast.makeText(
                    this,
                    "您有未授予的权限，可能影响使用",
                    Toast.LENGTH_SHORT
                ).show()
            }

        }
        player.setMediaItem(mediaItem)//准备媒体资源
        player.prepare()
        player.play()

    }// 授权结束

    override fun onPause() {
        super.onPause()
        player.pause()
    }
}